import React from "react";
import { formatMessage } from 'umi-plugin-react/locale';
import { Form, Input, Icon, message, Button, Pagination, Tooltip } from "antd";
import styles from "./editingStyle.less";
import EditSlot from "@/modules/EditSlot";
import UserSession from "@/UserSession";
import knowledgeHome from "@/services/knowledgeHome";
const { Search } = Input;

class SimilarQuestion extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			stdQuestion: "",
			similarQuestions: props.similarQuestionsList,
			moreQuestions: [],
			moreQuestionPage: 1,
			query: "",
			searchQuestion: [],
			showSlotIndex: -3,
			sourceData: [],
		};
	}

	componentDidMount() {
		if (this.props.onRef) {
			this.props.onRef(this);
		};
		if (this.props.secondDrawer) {
			console.log(this.props.stdQuestion);
			this.setStandQuestion(this.props.stdQuestion);
			this.setState({ moreQuestions: this.state.similarQuestions, });
		} else {
			if (this.props.stdQuestion) {
				this.setStandQuestion(this.props.stdQuestion);
			}
		}
	}

	addQuestion = (e) => {
		let { similarQuestions, moreQuestions } = this.state;
		const { secondDrawer } = this.props;
		let value = this.props.form.getFieldValue("similarQuestion");
		let flog = true;
		const that = this;
		if (value === "" || !value) {
			return message.error(formatMessage({ id: 'similarQuestion.error.questionEmpty' }));
		};
		if (secondDrawer) {
			flog = moreQuestions.some((q) => {
				if (q == value) {
					return true;
				}
			});
		} else {
			flog = similarQuestions.some((q) => {
				if (q == value) {
					return true;
				}
			});
		};

		if (flog) {
			return message.error(formatMessage({ id: 'similarQuestion.error.questionExists', values: { question: value } }));
		};
		if (secondDrawer) {
			moreQuestions.unshift(value);
		} else {
			similarQuestions.unshift(value);
		};
		knowledgeHome.postQaSimilarAdd();
		that.setState({ similarQuestions, moreQuestions, }, () => {
			that.props.form.resetFields(["similarQuestion"]);
		});
	};

	upQuestion = (k) => {
		let { similarQuestions, moreQuestions } = this.state;
		const { secondDrawer, form } = this.props;
		const stdQuestion = form.getFieldValue("stdQuestion");
		if (secondDrawer) {
			let index = moreQuestions.findIndex((item) => item == k);
			// moreQuestions[index] = moreQuestions.splice(index - 1, 1, moreQuestions[index])[0];
			moreQuestions[index] = stdQuestion;
			form.setFieldsValue({ stdQuestion: k });
		} else {
			let index = similarQuestions.findIndex((item) => item == k);
			// similarQuestions[index] = similarQuestions.splice(index - 1, 1, similarQuestions[index])[0];
			similarQuestions[index] = stdQuestion;
			form.setFieldsValue({ stdQuestion: k });
		};
		this.setState({ similarQuestions, moreQuestions, stdQuestion: k, });
	};

	delQuestion = (k, index) => {
		let { similarQuestions, moreQuestions, searchQuestion, query, moreQuestionPage, } = this.state;
		const { secondDrawer } = this.props;
		if (secondDrawer) {
			if (query) {
				searchQuestion = searchQuestion.filter((key) => key !== k);
			};
			moreQuestions = moreQuestions.filter((key) => key !== k);
		} else {
			similarQuestions = similarQuestions.filter((key) => key !== k);
		};

		//判断是否需要加载上一页数据 2022.4.8
		let minIndex = (moreQuestionPage - 1) * 10;
		let newMoreQuestionPage = moreQuestionPage;
		if (index == minIndex && moreQuestionPage > 1 && moreQuestions.length == index) {
			newMoreQuestionPage = moreQuestionPage - 1;
		};
		knowledgeHome.postQaSimilarDel();
		this.setState({ similarQuestions, moreQuestions, searchQuestion, }, () => {
			this.handelPageChange(newMoreQuestionPage);
		});
	};

	handelPageChange = (value) => {
		this.setState({ moreQuestionPage: value, });
	};

	handleSearch = (value) => {
		let { moreQuestions, moreQuestionPage, searchQuestion } = this.state;
		if (!value) {
			searchQuestion = moreQuestions;
		} else {
			searchQuestion = moreQuestions.filter((q) => q.indexOf(value) > -1);
		};
		moreQuestionPage = 1;
		this.setState({ searchQuestion, moreQuestionPage, query: value, });
	};

	setQuestions = (data) => {
		this.setState({ similarQuestions: data, });
	};

	setStandQuestion = (value) => {
		this.setState({ stdQuestion: value, }, () => {
			this.props.form.setFieldsValue({ stdQuestion: value });
		});
	};

	handelSimChangeByIndex = (e, index) => {
		let { similarQuestions, moreQuestions, searchQuestion, query } = this.state;
		const { secondDrawer } = this.props;
		if (this.props.secondDrawer) {
			if (query) {
				let orgValue = searchQuestion[index];
				let newIndex = moreQuestions.indexOf(orgValue);
				moreQuestions[newIndex] = e.target.value;
				searchQuestion[index] = e.target.value;
			} else {
				moreQuestions[index] = e.target.value;
			}
		} else {
			similarQuestions[index] = e.target.value;
		};
		this.setState({ similarQuestions, moreQuestions, searchQuestion, });
	};

	submitQuestions = () => {
		const { form } = this.props;
		const { similarQuestions } = this.state;
		let questionObj = {};
		form.validateFields((errors, values) => {
			if (!errors) {
				questionObj = {
					stdQuestion: values.stdQuestion,
					questions: similarQuestions,
				};
			}
		});
		return questionObj;
	};

	showMoreQuestionSetStdQuestion = (similarQuestions) => {
		let stdQuestion = this.props.form.getFieldValue("stdQuestion");
		this.setState({ stdQuestion, }, () => {
			this.props.showMoreQuestion(similarQuestions, stdQuestion);
		});
	};

	getStdQuestionForSecondDrawer = () => {
		return this.props.form.getFieldValue("stdQuestion");
	};

	showSlotByIndex = (index) => {
		this.setState({ showSlotIndex: index, });
	};

	addSlotToStd = (val) => {
		const { form } = this.props;
		let stdQuestion = form.getFieldValue("stdQuestion")
			? form.getFieldValue("stdQuestion")
			: "";
		stdQuestion = stdQuestion + "<" + val + ">";
		form.setFieldsValue({ stdQuestion });
		this.setState({ stdQuestion, });
	};

	addSlotToSim = (val) => {
		const { form } = this.props;
		let similarQuestion = form.getFieldValue("similarQuestion")
			? form.getFieldValue("similarQuestion")
			: "";
		similarQuestion = similarQuestion + "<" + val + ">";
		form.setFieldsValue({ similarQuestion });
	};

	addSlotToSimByIndex = (val, index) => {
		let { similarQuestions, moreQuestions } = this.state;
		if (this.props.secondDrawer) {
			moreQuestions[index] = moreQuestions[index] + "<" + val + ">";
		} else {
			similarQuestions[index] = similarQuestions[index] + "<" + val + ">";
		};
		this.setState({ similarQuestions, moreQuestions, });
	};

	pushSimilarQuestion = (questions, data) => {
		let { similarQuestions, sourceData } = this.state;
		sourceData = data;
		similarQuestions = Array.from(new Set([...questions, ...similarQuestions]));
		this.setState({ similarQuestions, moreQuestions: similarQuestions, sourceData, });
	};

	similarExtensionAsk = (data) => {
		this.setState({ similarQuestions: data })
	}

	render() {
		const { getFieldDecorator } = this.props.form;
		const { similarQuestions, moreQuestionPage, query, searchQuestion, stdQuestion, showSlotIndex } = this.state;
		let { moreQuestions } = this.state;
		const {
			secondDrawer, showMoreQuestion, similarQuestionsList, stdQuestionMore,
			authority, slotData, similarRef, questionId, urlPrefix,
		} = this.props;
		let minIndex = (moreQuestionPage - 1) * 10;
		let maxIndex = (moreQuestionPage - 1) * 10 + 10;
		if (query) {
			moreQuestions = searchQuestion;
		};
		const formItemLayout = {
			labelCol: {
				xs: { span: 24 },
				sm: { span: 3 },
			},
			wrapperCol: {
				xs: { span: 24 },
				sm: { span: 21 },
			},
		};
		const formItemForSimilar = {
			wrapperCol: {
				xs: { span: 24 },
				sm: { span: 22, offset: 2 },
			},
		};
		return (
			<Form {...formItemLayout}>
				{!secondDrawer ? ("") : (
					<Form.Item {...formItemForSimilar}>
						<Search
							placeholder={formatMessage({ id: 'similarQuestion.search.placeholder' })}
							style={{ width: "80%", height: 40, border: "1px solid #F0F0F0" }}
							onSearch={this.handleSearch}
						/>
					</Form.Item>
				)}
				<Form.Item label={formatMessage({ id: 'similarQuestion.form.stdQuestion.label' })}>
					{getFieldDecorator("stdQuestion", {
						rules: [{ required: true, message: formatMessage({ id: 'similarQuestion.form.stdQuestion.required' }) }],
					})(
						<Input
							placeholder={formatMessage({ id: 'similarQuestion.form.stdQuestion.placeholder' })}
							style={{ width: "80%", height: 40, border: "1px solid #F0F0F0" }}
							disabled={authority === 1 || urlPrefix}
							maxLength={100}
							onFocus={() => this.showSlotByIndex(-2)}
						/>
					)}
					{showSlotIndex === -2 ? (
						<EditSlot slots={slotData} click={this.addSlotToStd} />
					) : ("")}
				</Form.Item>
				{urlPrefix ? null : (
					<Form.Item label={formatMessage({ id: 'similarQuestion.form.similarQuestion.label' })}>
						{getFieldDecorator("similarQuestion")(
							<Input
								placeholder={formatMessage({ id: 'similarQuestion.form.similarQuestion.placeholder' })}
								onPressEnter={this.addQuestion}
								style={{ width: "80%", height: 40, border: "1px solid #F0F0F0" }}
								disabled={authority === 1}
								maxLength={100}
								onFocus={() => this.showSlotByIndex(-1)}
							/>
						)}
						{authority === 1 ? ("") : (
							<span style={{ marginLeft: 10 }}>
								<Icon type='plus-circle' className={styles.icons} onClick={this.addQuestion} />
							</span>
						)}
						{showSlotIndex == -1 ? (
							<EditSlot slots={slotData} click={this.addSlotToSim} />
						) : ("")}
					</Form.Item>
				)}

				{urlPrefix ? null : !secondDrawer ? similarQuestions.map((item, index) => {
					return index > -1 && index < 5 ? (
						<Form.Item {...formItemForSimilar} key={index}>
							<Input
								value={item}
								style={{ width: "80%", height: 40, border: "1px solid #F0F0F0" }}
								onChange={(e) => this.handelSimChangeByIndex(e, index)}
								disabled={authority === 1}
								maxLength={100}
								onFocus={() => this.showSlotByIndex(index)}
							/>
							{authority === 1 ? ("") : (
								<span style={{ marginLeft: 10 }}>
									<Tooltip title={formatMessage({ id: 'similarQuestion.action.setAsStdQuestion' })}>
										<Icon type='vertical-align-top' className={styles.icons} style={{ marginRight: 10 }} onClick={() => this.upQuestion(item)} />
									</Tooltip>
									{urlPrefix ? null : (
										<Icon type='close-circle' className={styles.icons} onClick={() => this.delQuestion(item)} />
									)}
								</span>
							)}
							{index == showSlotIndex ? (
								<EditSlot slots={slotData} click={(e) => this.addSlotToSimByIndex(e, index)} />
							) : ("")}
						</Form.Item>
					) : ("");
				}) : moreQuestions.map((item, index) => {
					return (index > minIndex || index === minIndex) && index < maxIndex ? (
						<Form.Item {...formItemForSimilar} key={index}>
							<Input
								value={item}
								style={{ width: "80%", height: 40, border: "1px solid #F0F0F0" }}
								onChange={(e) => this.handelSimChangeByIndex(e, index)}
								disabled={authority === 1}
								maxLength={100}
								onFocus={() => this.showSlotByIndex(index)}
							/>
							<span style={{ marginLeft: 10 }}>
								{!query && authority != 1 ? (
									<Tooltip title={formatMessage({ id: 'similarQuestion.action.setAsStdQuestion' })}>
										<Icon
											type='vertical-align-top'
											className={styles.icons}
											style={{ marginRight: 10 }}
											onClick={() => this.upQuestion(item)}
											title={formatMessage({ id: 'similarQuestion.action.setAsStdQuestion' })}
										/>
									</Tooltip>
								) : ("")}
								{authority === 1 || urlPrefix ? ("") : (
									<Icon
										type='close-circle'
										className={styles.icons}
										onClick={() => this.delQuestion(item, index)}
									/>
								)}
							</span>
							{index == showSlotIndex ? (
								<EditSlot slots={slotData} click={(e) => this.addSlotToSimByIndex(e, index)} />
							) : ("")}
						</Form.Item>
					) : ("");
				})}
				{urlPrefix ? null : !secondDrawer && similarQuestions.length > 5 ? (
					<Form.Item {...formItemForSimilar} style={{textAlign:'center'}}>
						<Button onClick={() => this.showMoreQuestionSetStdQuestion(similarQuestions)}>{formatMessage({ id: 'similarQuestion.action.viewMore' })}</Button>
					</Form.Item>
				) : ("")}
				{urlPrefix ? null : secondDrawer ? (
					<div style={{ textAlign: "center" }}>
						<Pagination current={moreQuestionPage} total={moreQuestions.length} size={10} onChange={this.handelPageChange} />
					</div>
				) : ("")}
			</Form>
		);
	}
}

export default Form.create()(SimilarQuestion);
